/**
 * Copyright (c) 2014-2015, Suredy technology Co., Ltd. All rights reserved.
 * @author ZhangMaoren 
 * @since 2015年6月17日
 * @version 0.1
 */
package com.suredy.security.ctrl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.suredy.Constants;
import com.suredy.core.ctrl.BaseCtrl;
import com.suredy.core.mvc.model.MessageModel;
import com.suredy.security.entity.OrgEntity;
import com.suredy.security.entity.PermissionEntity;
import com.suredy.security.entity.RoleEntity;
import com.suredy.security.entity.UnitEntity;
import com.suredy.security.entity.User2PermissionEntity;
import com.suredy.security.entity.User2RoleEntity;
import com.suredy.security.entity.UserEntity;
import com.suredy.security.model.Action;
import com.suredy.security.model.Org;
import com.suredy.security.model.Role;
import com.suredy.security.model.User;
import com.suredy.security.model.User2Role;
import com.suredy.security.service.OrgSrv;
import com.suredy.security.service.PermissionSrv;
import com.suredy.security.service.RoleSrv;
import com.suredy.security.service.UnitSrv;
import com.suredy.security.service.User2PermissionSrv;
import com.suredy.security.service.User2RoleSrv;
import com.suredy.security.service.UserSrv;


/**
 * @author ZhangMaoren
 *
 */
@Controller
@RequestMapping(value="/config")
public class UserCtrl extends BaseCtrl{
	private final static Logger log = LoggerFactory.getLogger(UserCtrl.class);

	@Autowired
	private User2RoleSrv user2roleSrv;
	
	
	@Autowired
	private User2PermissionSrv user2permissionSrv;

	@Autowired
	private UserSrv userSrv;
	
	@Autowired
	private RoleSrv roleSrv;
		
	@Autowired
	private UnitSrv unitSrv;
	
	@Autowired
	private PermissionSrv permissionSrv;
	
	@Autowired
	private OrgSrv  orgSrv;
	/**
	 * get user list
	 * 
	 * @param type
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "user/list")
	public ModelAndView getUsers(String page, String size) {
		ModelAndView view = new ModelAndView("/config/security/user-list");
		int pageIndex = 1, pageSize = Constants.DEFAULT_PAGE_SIZE;
		if (!StringUtils.isBlank(page)) {
			pageIndex = Integer.parseInt(page);
		} 
		if(!StringUtils.isBlank(size)) {
			pageSize = Integer.parseInt(size);
		}
		Long count = this.userSrv.Count();
		List<User> data = this.userSrv.getAll(pageIndex, pageSize);
		view.addObject("data", data);
		view.addObject("pageSize", pageSize);
		view.addObject("pageIndex", pageIndex);
		view.addObject("count", count);
		return view;
	}
	
	
	@RequestMapping(value = "user/create")
	public ModelAndView createUser() {
		ModelAndView view = new ModelAndView("/config/security/user-create");
		List<Org> orgs = this.orgSrv.getAll();
		view.addObject("orgs", orgs);
		return view;
	}
	
	private String generateCode(UnitEntity unit) {
		int sn = unit.getId().hashCode() +  this.userSrv.countUsers(unit.getId()) + 1;
		String temp = "" + sn;
		return "A" + temp.substring(2);
	}
	
	@RequestMapping("user/create-save")
	@ResponseBody
	public Object doCreateRole(HttpServletRequest request) {
		String unitId = request.getParameter("unitId");
		//String uniqueCode = request.getParameter("loginId");
		//String password = request.getParameter("initPassword");
		//String code = request.getParameter("code");
		String name = request.getParameter("name");
		String alias = request.getParameter("alias");
		String title = request.getParameter("title");
		String email = request.getParameter("email");
		String sort = request.getParameter("sort");
		String description = request.getParameter("description");
		
		if (StringUtils.isBlank(name)) {
			return MessageModel.createErrorMessage("参数不足: 用户姓名必须提供", null);
		}
		
		UnitEntity unit = this.unitSrv.get(unitId);
		OrgEntity org = unit.getOrg();
		String code = generateCode(unit); 
		UserEntity user = new UserEntity();
		user.setActionType(0);
		user.setActUserId(null);
		user.setAlias(StringUtils.isBlank(alias) ? null : alias);
		user.setAvailable(1);
		user.setCode(code);
		user.setDescription(StringUtils.isBlank(description) ? null : description);
		user.setDominoName(null);
		user.setEmail(StringUtils.isBlank(email) ? null : email);
		user.setIsMailUser(0);
		user.setName(name);
		user.setPassword("1");
		user.setSort(StringUtils.isBlank(sort) ? 0 : Integer.parseInt(sort));
		user.setTitle(StringUtils.isBlank(title) ? null : title);
		user.setUniqueCode("U=" + code + "/" + unit.getUniqueCode());
		user.setFullName(name + "/" + unit.getFullName());
		user.setUnit(unit);
		user.setUnitUC(unit.getUniqueCode());
		
		user.setOrg(org);
		this.userSrv.save(user);
		
		return MessageModel.createSuccessMessage(null, null);
	}
	
	@RequestMapping(value = "user/edit")
	public ModelAndView eidtUser(String userId) {
		ModelAndView view = new ModelAndView("/config/security/user-edit");
		if (StringUtils.isBlank(userId)) {
			log.info("Parameter String[userId] is blank.");
			return view;
		}
		User user = this.userSrv.getById(userId);
		view.addObject("user", user);
		return view;
	}
	
	@RequestMapping("user/edit-save")
	@ResponseBody
	public Object doEidtUser(HttpServletRequest request) {
		String id = request.getParameter("id");
		String unitId = request.getParameter("unitId");
		String name = request.getParameter("name");
		String alias = request.getParameter("alias");
		String title = request.getParameter("title");
		String email = request.getParameter("email");
		String sort = request.getParameter("sort");
		String description = request.getParameter("description");		
		if (StringUtils.isBlank(id) ||  StringUtils.isBlank(name)) {
			return MessageModel.createErrorMessage("参数不足: 用户ID,用户姓名必须提供", null);
		}
		OrgEntity org = null;
		UnitEntity unit = null;

		UserEntity user = this.userSrv.get(id);
		user.setAlias(StringUtils.isBlank(alias) ? null : alias);
		user.setDescription(StringUtils.isBlank(description) ? null : description);
		user.setEmail(StringUtils.isBlank(email) ? null : email);
		user.setName(name);
		user.setSort(StringUtils.isBlank(sort) ? 0 : Integer.parseInt(sort));
		user.setTitle(StringUtils.isBlank(title) ? null : title);
		
		unit = this.unitSrv.get(unitId);
		org = unit.getOrg();
		user.setFullName(name + "/" + unit.getFullName());
		user.setUnit(unit);
		user.setUnitUC(unit.getUniqueCode());
		
		user.setOrg(org);
		
		this.userSrv.update(user);
		return MessageModel.createSuccessMessage(null, null);
	}
	
	@RequestMapping("user/delete")
	@ResponseBody
	public Object doEidtDelete(String userId) {	
		if (StringUtils.isBlank(userId)) {
			return MessageModel.createErrorMessage("用户ID必须提供", null);
		}
		UserEntity user = this.userSrv.get(userId);
		if (user == null) {
			return MessageModel.createErrorMessage("未找到与ID['"+ userId +"']对应的用户信息", null);
		}
		
		this.userSrv.delete(user);
		return MessageModel.createSuccessMessage(null, null);
	}
	
	@RequestMapping(value = "user/permission")
	public ModelAndView User2Permission(String userId) {
		ModelAndView view = new ModelAndView("/config/security/user2permission");
		User user = this.userSrv.getById(userId);
		view.addObject("user", user);
		return view;

	}
	
	@Transactional
	@RequestMapping("user/permission-save")
	@ResponseBody
	public Object User2ResourceSave(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (StringUtils.isBlank(id)) {
			log.error("Parameter String[id] is blank.");
			return MessageModel.createErrorMessage("用户ID必须提供", null);
		}
		
		//删除全部role2permission引用
		List<User2PermissionEntity> userPermissions = this.user2permissionSrv.getByUser(id);
		for (User2PermissionEntity rp : userPermissions) {
			this.user2permissionSrv.delete(rp);
		}
		
		for (Action action : Action.values()) {			
			//新的user2permission引用
			String data =  request.getParameter("resources");
			if (!StringUtils.isBlank(data)) {
				String[] resourceIds = data.split("-");
				if (resourceIds != null && resourceIds.length > 0) {
					for (String resourceId : resourceIds) {
						PermissionEntity permission = this.permissionSrv.GetOrCreate(resourceId,  action.getAction());
						User2PermissionEntity up = new User2PermissionEntity();
						up.setPermission(permission);
						UserEntity user = new UserEntity();
						user.setId(id);
						up.setUser(user);
						this.user2permissionSrv.save(up);
					} 
				}
			}
		}

		return MessageModel.createSuccessMessage(null, null);
	}
	
	@RequestMapping(value = "user/role")
	public ModelAndView User2Role(String userId) {
		ModelAndView view = new ModelAndView("config/security/user2role");
		User user = this.userSrv.getById(userId);
		List<Role> roles = this.roleSrv.getAll();
		
		List<User2RoleEntity> pos = this.user2roleSrv.getByUser(userId);
		List<User2Role> relations = new ArrayList<User2Role>();
		for (User2RoleEntity po : pos) {
			relations.add(po.toVO());
		}
		view.addObject("user", user);
		view.addObject("relations", relations);
		view.addObject("roles", roles);
		return view;
	}

	@Transactional
	@RequestMapping("user/role-save")
	@ResponseBody
	public Object User2RoleSave(HttpServletRequest request) {
		String id = request.getParameter("id");
		if (StringUtils.isBlank(id)) {
			log.error("Parameter String[id] is blank.");
			return MessageModel.createErrorMessage("用户ID必须提供", null);
		}
		// 删除全部user2role引用
		List<User2RoleEntity> relations = this.user2roleSrv.getByUser(id);
		for (User2RoleEntity ur : relations) {
			this.user2roleSrv.delete(ur);
		}
		// 加入新的user2role引用
		String[] roleIds = request.getParameterValues("roleId");
		if (roleIds != null && roleIds.length > 0) {
			for (String roleId : roleIds) {
				User2RoleEntity ur = new User2RoleEntity();
				UserEntity user = new UserEntity();
				user.setId(id);
				ur.setUser(user);
				RoleEntity role = new RoleEntity();
				role.setId(roleId);
				ur.setRole(role);
				this.user2roleSrv.save(ur);
			}
		}
		return MessageModel.createSuccessMessage(null, null);
	}
}
